package com.polaris.live.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.StringUtils
import com.google.firebase.ktx.Firebase
import com.google.firebase.messaging.ktx.messaging
import com.just.agentweb.AgentWebConfig
import com.polaris.live.App
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.network.AppException
import com.polaris.live.common.network.request
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.network.requestNoCheck
import com.polaris.live.common.network.state.ResultState
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.UserConst.SettingType
import com.polaris.live.constant.UserConst.UserSetting
import com.polaris.live.net.userService
import com.polaris.live.resp.back_resp.ThirdBindResp
import com.polaris.live.resp.go_resp.FeedbackBean
import com.polaris.live.resp.go_resp.SettingModifyBean
import com.polaris.live.resp.go_resp.ThirdBindBean
import com.polaris.live.translation.R
import com.polaris.live.utils.CommonUtils.toBoolean
import com.polaris.live.utils.file.FileUtils
import com.polaris.live.viewmodel.login.LoginViewModel
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * SetViewModel
 *
 * @author Created by 半仙 on 2023/08/25 06:35
 * @since 1.0.0
 */
class SetViewModel : LoginViewModel() {

    /**
     * 反馈与建议
     */
    val feedbackLiveData = MutableLiveData<ResultState<Any>>()
    fun feedback(feedbackBean: FeedbackBean) {
        requestLoading({ userService.feedback(feedbackBean) }, feedbackLiveData)
    }

    /**
     * 登出
     */
    val logoutLiveData = MutableLiveData<ResultState<Any>>()
    fun logout() {
        requestLoading({ userService.logout() }, logoutLiveData)
    }

    /**
     * 获取缓存
     */
    val cacheSizeLiveData = MutableLiveData<String?>()
    fun getCacheSize() {
        viewModelScope.launch {
            val size = withContext(CoroutineScopeManager.ioDispatcher) {
                val appCachePath = FileUtils.getCacheDir()
                val webCachePath = AgentWebConfig.getCachePath(App.instance)
                val appSizeDef = async { FileUtils.getFileSize(appCachePath) }
                val webSizeDef = async { FileUtils.getFileSize(webCachePath) }

                FileUtils.formatFileSize((appSizeDef.await() + webSizeDef.await()).toFloat())
            }

            cacheSizeLiveData.value = size
        }
    }

    /**
     * 清除缓存
     */
    fun clearCache() {
        viewModelScope.launch {
            withContext(CoroutineScopeManager.ioDispatcher) {
                com.blankj.utilcode.util.FileUtils.delete(FileUtils.getCacheDir())
                AgentWebConfig.clearDiskCache(App.instance)
            }

            cacheSizeLiveData.value = "0.00B"
        }
    }

    /**
     * 注销账号
     */
    val terminateLiveData = MutableLiveData<ResultState<Any>>()
    fun cancelAccount() {
        requestLoading({ userService.terminate() }, terminateLiveData)
    }

    /**
     * 三方绑定情况查询
     */
    val thirdBindLiveData = MutableLiveData<ResultState<List<ThirdBindResp>>>()
    fun getThirdBind() {
        request({ userService.getThirdBind() }, thirdBindLiveData)
    }

    /**
     * google绑定
     */
    val googleBindLiveData = MutableLiveData<ResultState<Any>>()
    fun googleBind(id: String, token: String) {
        val loginPhoneBean = ThirdBindBean(id, token, 1)
        request({ userService.thirdBind(loginPhoneBean) }, googleBindLiveData)
    }

    /**
     * 修改用户设置
     */
    val settingLiveData = MutableLiveData<Pair<Int, Int>>()
    val settingErrorLiveData = MutableLiveData<AppException>()
    fun settingModify(@SettingType type: Int, state: Int) {
        requestNoCheck({ userService.settingModify(SettingModifyBean(type, state)) }, {
            if (it.isSuccess()) {
                when (type) {
                    UserSetting.LIVE_NOTICE -> {
                        UserManager.getUser().setting?.liveNotice = state
                    }

                    UserSetting.CHAT_NOTICE -> {
                        UserManager.getUser().setting?.chatNotice = state
                    }

                    UserSetting.CALL_NOTICE -> {
                        UserManager.getUser().setting?.callNotice = state
                    }

                    UserSetting.MESSAGE_DND -> {
                        UserManager.getUser().setting?.messageDnd = state
                    }

                    UserSetting.LUCKY_BAG_NOTICE -> {
                        UserManager.getUser().setting?.luckyBagNotice = state

                        if (state == AppConst.YES) {
                            Firebase.messaging.subscribeToTopic(CommonConst.FirebaseTopic.LUCKY_BAG)
                        } else {
                            Firebase.messaging.unsubscribeFromTopic(CommonConst.FirebaseTopic.LUCKY_BAG)
                        }
                    }

                    UserSetting.INVITE_DO_NOT_DISTURB -> {
                        if (state.toBoolean()) {
                            ToastGravity.showGravity(StringUtils.getString(R.string.setting_invite_open_success))
                        } else {
                            ToastGravity.showGravity(StringUtils.getString(R.string.close_success_other_send_invitation))
                        }
                        UserManager.getUser().setting?.roomInviteDnd = state
                    }
                }
                settingLiveData.value = Pair(type, state)
            } else {
                settingErrorLiveData.value = AppException(it.code, it.errorMessage ?: "", it.ext)
                ToastGravity.showGravity(it.errorMessage)
            }
        })
    }
}